<template>
  <div>
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="request" :rules="rules" size="small" label-width="110px" label-position="left" v-if="request">
        <el-form-item label="订单号：" prop="orderId">
          {{request.orderId}}
        </el-form-item>

        <el-form-item label="申请产品：" prop="productTitle">
          {{request.productTitle}}
        </el-form-item>

        <el-form-item label="收货地址" prop="addressId">
          <el-radio-group class="md-address-radio" v-model="request.addressId">
            <el-row v-for="item in addressDataList" :key="item.addressId">
              <el-col :span="20">
                <el-radio :label="item.addressId">
                  <p>{{item.country}}/{{item.province}}/{{item.city}}/{{item.district}}</p>
                  <p>{{item.address??'---'}}</p>
                  <p>{{item.name??'---'}}：{{item.email??'---'}}、{{item.phone??'---'}}</p>
                </el-radio>
              </el-col>
              <el-col :span="4">
                <el-button type="text" @click="handleAddressUpdate(item)">编辑</el-button>
                <el-button type="text" @click="handleAddressDel(item)">删除</el-button>
              </el-col>
            </el-row>
          </el-radio-group>
          <br />
          <el-button type="primary" @click="handleAddressInsert()">新增收货地址</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleSubmit()">确认发货</el-button>
        <el-button size="small" @click="handleCancel()">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="addressDialog.title" :visible.sync="addressDialog.open" width="780px" append-to-body :close-on-click-modal="false">
      <el-form ref="addressForm" :model="addressDialog.request" :rules="addressDialog.rules" size="small" label-width="110px" label-position="right">
        <el-form-item label="联系人姓名：" prop="name">
          <el-input v-model="addressDialog.request.name" placeholder="请输入姓名" style="width: 100%" />
        </el-form-item>

        <el-form-item label="电话号码：" prop="phone">
          <el-input v-model="addressDialog.request.phone" placeholder="请输入手机号" />
        </el-form-item>

        <el-form-item label="联系邮箱：" prop="email">
          <el-input v-model="addressDialog.request.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-row>
          <el-col :span="12" class="pr5">
            <el-form-item label="国家：" prop="country">
              <md-country v-model="addressDialog.request.country" @change="handleCountryChange" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="pl5">
            <el-form-item label="省：" prop="province">
              <el-input v-model="addressDialog.request.province" placeholder="请输入省" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" class="pr5">
            <el-form-item label="州：" prop="city">
              <el-input v-model="addressDialog.request.city" placeholder="请输入州" />
            </el-form-item>
          </el-col>
          <el-col :span="12" class="pl5">
            <el-form-item label="区：" prop="district">
              <el-input v-model="addressDialog.request.district" placeholder="请输入区" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="详细地址" prop="address">
          <el-input type="textarea" v-model="addressDialog.request.address" :rows="5" placeholder="请输入详细地址" />
        </el-form-item>

        <el-form-item label="邮编：" prop="zipCode">
          <el-input v-model="addressDialog.request.zipCode" placeholder="请输入邮编" />
        </el-form-item>

        <el-form-item label="默认地址：" prop="isDefault">
          <md-dict-radio-group radio="button" :options="dictData['md_addtess_default']" v-model="addressDialog.request.isDefault"></md-dict-radio-group>
        </el-form-item>

        <el-form-item label="状态：" prop="status">
          <md-dict-radio-group radio="button" :options="dictData['sys_normal_disable']" v-model="addressDialog.request.status"></md-dict-radio-group>
        </el-form-item>

        <el-form-item label="备注：" prop="remark">
          <el-input type="textarea" v-model="addressDialog.request.remark" :rows="5" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="handleAddressSubmit">确 定</el-button>
        <el-button size="small" @click="handleAddressCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateProductOrder } from '@/api/web/product.order.service.js'
import { listAddress, insertAddress, updateAddress, delAddress, getAddress } from '@/api/web/address.service.js'
import VueCountryIntl from 'vue-country-intl'
import 'vue-country-intl/lib/vue-country-intl.css'
import { mdGetDictData } from '@/ddd/dict.service.js'
export default {
  name: 'MdOrderShipDialogComponent',
  components: {
    'md-country': VueCountryIntl
  },
  props: {
    data: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      title: '订单发货',
      open: false,
      request: { ...this.data },
      rules: { ...requestRules },
      addressDataList: [],
      addressDialog: {
        open: false,
        title: '添加收货地址',
        request: { ...addressRequestParams },
        rules: { ...addressRequestRules },
      },
      dictData: {}
    }
  },
  watch: {
    data: {
      handler (_data) {
        this.request = { ..._data }
        if (this.request.userId) {
          this.getAddressDataList()
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    mdGetDictData(['sys_normal_disable', 'md_addtess_default']).then(res => {
      this.dictData = res
    })
  },
  methods: {
    handleOpen () {
      this.open = true
    },
    handleCancel () {
      this.open = false

      const request = Object.assign({}, { ...this.request })

      const keys = Object.keys(request)
      if (keys.length > 0) {
        keys.forEach(key => {
          delete request[key]
        })
      }

      this.request = { ...request }

      this.addressDataList = []
    },
    handleSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = {
            orderId: this.request.orderId,
            addressId: this.request.addressId,
            status: '5'
          }

          await updateProductOrder(params)

          this.$message.success('操作成功')

          this.handleCancel()

          this.$emit('refresh')
        } catch (error) {
          console.log(error)
        }
      })
    },
    async getAddressDataList () {
      try {
        const res = await listAddress({ userId: this.request.userId })

        this.addressDataList = res.data
      } catch (error) {
        console.log(error)
      }
    },
    handleCountryChange (event) {
      this.addressDialog.request.countryName = event.name
    },
    handleAddressReset () {
      this.addressDialog.request = { ...addressRequestParams }
      if (this.$refs.addressForm) {
        this.$refs.addressForm.resetFields()
      }
    },
    async handleAddressInsert () {
      this.addressDialog.request.userId = this.request.userId

      this.addressDialog.open = true
    },
    async handleAddressUpdate (row) {
      try {
        this.handleAddressReset()

        const res = await getAddress(row.addressId)

        const data = res.data

        data.country = parseInt(data.country ?? '0'.split(',')[0])
        data.countryName = data.country ?? ''.split(',')[1]

        this.addressDialog.request = data

        this.addressDialog.open = true

        this.addressDialog.title = '修改收货地址'

      } catch (error) {
        console.log(error)
      }
    },
    async handleAddressDel (row) {
      try {
        const ids = row?.addressId || this.tableSelectIds

        await this.$confirm(`是否确认删除编号为${ids}的数据项？`)

        await delAddress(ids)

        this.$message.success('删除成功')

        this.getAddressDataList()
      } catch (error) {
        console.log(error)
      }
    },
    async handleAddressSubmit () {
      this.$refs.addressForm.validate(async valid => {
        if (!valid) {
          return
        }

        try {
          const params = Object.assign({}, { ...this.addressDialog.request })

          params.country = `${params.country},${params.countryName}`

          await (params.addressId === undefined ? insertAddress : updateAddress)(params)

          this.$message.success(params.addressId === undefined ? '添加成功' : '修改成功')

          this.getAddressDataList()

          this.handleAddressCancel()
        } catch (error) {
          console.log(error)
        }
      })
    },
    handleAddressCancel () {
      this.addressDialog.open = false
      this.addressDialog.request = { ...addressRequestParams }
    }
  }
}

const requestRules = {
  addressId: [{ required: true, message: '请选择收货地址', trigger: 'change' }]
}

const addressRequestParams = {
  addressId: undefined,
  name: undefined,
  phone: undefined,
  email: undefined,
  region: undefined,
  regionLabels: undefined,
  country: undefined,
  countryName: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  zipCode: undefined,
  address: undefined,
  userId: undefined,
  addressType: '0',
  isDefault: '1',
  status: '0'
}

const addressRequestRules = {
  name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话号码', trigger: 'blur' }],
  email: [{ required: true, message: '请输入联系邮箱', trigger: 'blur' }],
  country: [{ required: true, message: '请选择国家', trigger: 'change' }],
  province: [{ required: true, message: '请输入省', trigger: 'blur' }],
  city: [{ required: true, message: '请输入州', trigger: 'blur' }],
  district: [{ required: true, message: '请输入区', trigger: 'blur' }],
  zipCode: [{ required: true, message: '请输入邮编', trigger: 'blur' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  userId: [{ required: true, message: '请选择所属用户', trigger: 'change' }]
}
</script>

<style lang="less" scoped>
::v-deep .vue-country-intl {
  cursor: pointer;

  .country-intl-input-wrap {
    overflow: hidden;
    input {
      height: 33px !important;
    }
    .country-intl-label {
      height: 33px !important;
      box-sizing: border-box;
      padding: 0px 10px !important;
    }
  }

  .vue-country-list-wrap {
    max-height: 200px !important;
    .vue-country-list {
      .vue-country-item {
        padding: 0px 10px !important;
      }
    }
  }
}

.md-address-radio {
  display: block;
  width: 100%;
  box-sizing: border-box;
  border: 1px solid #efefef;
  padding: 10px;

  .el-row {
    border-bottom: 1px solid #efefef;
    margin-bottom: 15px;
    padding-bottom: 10px;

    &:last-child {
      border-bottom: none !important;
      margin-bottom: 0px;
      padding-bottom: 0px;
    }
  }
  .el-radio {
    display: flex;

    .el-radio__label {
      p {
        margin-bottom: 10px;
      }
    }
  }
}
</style>